﻿using B.S.ProcessEgine.ErrorCode;
using Microsoft.AspNetCore.Mvc.Filters;

namespace B.S.ProcessEgine.API.Extensions
{
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GlobalExceptionFilter> _logger;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="logger"></param>
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            //写异常日志
            _logger.LogError("【全局异常过滤器】：" + context.Exception.Message);
            //异常已经处理
            context.ExceptionHandled = true;

            //返回500错误
            context.Result = new Microsoft.AspNetCore.Mvc.ObjectResult(new
            {
                code = (int)StateCodeEnum.Exception,
                message = context.Exception.Message
            })
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };

            return Task.CompletedTask;
        }
    }
}
